package com.imooc.bilibili.service;

import com.imooc.bilibili.constant.AuthRoleConstant;
import com.imooc.bilibili.domain.auth.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserAuthService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private AuthRoleService authRoleService;

    /**
     * 获取用户的权限列表
     * @param userId
     * @return
     */
    public UserAuthorities getUserAuthorities(Long userId) {
        // 获取用户角色列表
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        // 抽取角色id
        Set<Long> roleIdSet = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        List<AuthRoleElementOperation> authRoleElementOperations = null;
        List<AuthRoleMenu> authRoleMenusList = null;
        if (roleIdSet != null) {
            // 查询角色所具有的操作权限
            authRoleElementOperations =  authRoleService.getRoleElementOperationsByRoleIds(roleIdSet);
            // 查询角色所具有的页面菜单
            authRoleMenusList = authRoleService.getAuthRoleMenusByRoleIds(roleIdSet);
        }

        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleElementOperationList(authRoleElementOperations);
        userAuthorities.setRoleMenuList(authRoleMenusList);
        return userAuthorities;
    }

    /**
     * 添加用户默认权限角色
     * @param id
     */
    public void addUserDefaultRole(Long id) {
        UserRole userRole = new UserRole();
        AuthRole authRole = userRoleService.getRoleByCode(AuthRoleConstant.ROLE_LV0);
        userRole.setUserId(id);
        userRole.setRoleId(authRole.getId());
        userRoleService.addUserRole(userRole);
    }
}
